package com.sfh.cpc;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.library.AutoFlowLayout;
import com.example.library.FlowAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sfh.cpc.com.entity.RxEventSearch;
import com.sfh.cpc.mass.MassSearchFragment;
import com.sfh.cpc.note.SearchNoteFragment;
import com.sfh.cpc.user.UserSearchFragment;
import com.sfh.lib.AppCacheManager;
import com.sfh.lib.rx.ui.UtilRxView;
import com.sfh.lib.ui.AbstractLifecycleActivity;
import com.sfh.lib.ui.AbstractLifecycleFragment;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * 功能描述:
 * 搜索
 *
 * @date 2019/6/11
 */
public class SearchActivity extends AbstractLifecycleActivity {
    public static void start(Context context) {
        Intent intent = new Intent(context, SearchActivity.class);
        context.startActivity(intent);
    }
    private EditText etSearch;
    private View fyLayout;
    private LinearLayout lySearch;
    private TextView tvHistory;
    private AutoFlowLayout historyFlexboxLayout;
    private TabLayout tabLayout;
    private ViewPager viewPager;



    private List<String> mData;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home_search_activity);
        initView();
    }

    private void initView() {
        etSearch = findViewById(R.id.et_search);
        fyLayout =  findViewById(R.id.ly_layout);
        lySearch = findViewById(R.id.ly_search);
        tvHistory =  findViewById(R.id.tv_history);
        historyFlexboxLayout =  findViewById(R.id.history_flexboxLayout);
        tabLayout =  findViewById(R.id.tab_layout);
        viewPager =  findViewById(R.id.view_pager);

        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        historyFlexboxLayout.setOnItemClickListener(new AutoFlowLayout.OnItemClickListener() {
            @Override
            public void onItemClick(int i, View view) {
                lySearch.setVisibility(View.GONE);
                etSearch.setText(mData.get(i));
                etSearch.setSelection(mData.get(i).length());
            }
        });
        String history = AppCacheManager.getCache(HISTORY_KEY, String.class);
        if (TextUtils.isEmpty(history)) {
            mData = new ArrayList<>(5);
            tvHistory.setVisibility(View.GONE);
            historyFlexboxLayout.setVisibility(View.GONE);
        } else {
            //历史记录
            tvHistory.setVisibility(View.VISIBLE);
            historyFlexboxLayout.setVisibility(View.VISIBLE);

            mData = new Gson().fromJson(history,new TypeToken<List<String>>(){}.getType());
            historyFlexboxLayout.setAdapter(new FlowAdapter<String>(mData) {
                @Override
                public View getView(int i) {
                    return getTextView(getItem(i));
                }
            });
        }

        Disposable disposable = UtilRxView.afterTextChangeEvents(etSearch, 800).subscribe(new Consumer<CharSequence>() {
            @Override
            public void accept(CharSequence cotent) throws Exception {

                if (TextUtils.isEmpty(cotent)) {
                    lySearch.setVisibility(View.VISIBLE);
                    fyLayout.setVisibility(View.GONE);

                } else {
                    lySearch.setVisibility(View.GONE);
                    fyLayout.setVisibility(View.VISIBLE);
                    tvHistory.setVisibility(View.VISIBLE);
                    historyFlexboxLayout.setVisibility(View.VISIBLE);

                    postEvent(new RxEventSearch(cotent.toString()));
                    addHistory(cotent);
                }
            }
        });
        this.putDisposable(disposable);

        Adapter adapter = new Adapter(getSupportFragmentManager());
        this.viewPager.setAdapter(adapter);
        this.viewPager.setOffscreenPageLimit(1);
        this.tabLayout.setupWithViewPager( this.viewPager);
    }

    private static final String HISTORY_KEY = "HISTORY_KEY";

    private void addHistory(CharSequence content) {

        if (!mData.contains(content.toString())) {

            mData.add(content.toString());
            AppCacheManager.putCache(HISTORY_KEY, new Gson().toJson(mData), true);
            historyFlexboxLayout.clearViews();
            historyFlexboxLayout.setAdapter(new FlowAdapter<String>(mData) {
                @Override
                public View getView(int i) {
                    return getTextView(getItem(i));
                }
            });
        }
    }

    private View getTextView(CharSequence content) {
        View view = View.inflate(this, R.layout.home_search_item, null);
        TextView tv = view.findViewById(R.id.tv);
        tv.setText(content);
        return view;
    }


    class Adapter extends FragmentPagerAdapter {

        List<AbstractLifecycleFragment> fragments = new ArrayList<>(3);

        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            return fragments.get(position).getName();
        }

        public Adapter(FragmentManager fm) {
            super(fm);
            fragments.add(SearchNoteFragment.newFragment());
            fragments.add(MassSearchFragment.newFragment());
            fragments.add(UserSearchFragment.newFragment());
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }
    }


}
